/**
 * 
 */
package com.wubo.sec.service.impl;

import java.util.HashSet;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;

import com.wubo.sec.bean.UserAuthRelate;
import com.wubo.sec.config.LangUtil;
import com.wubo.sec.event.AuthorityEvent;
import com.wubo.sec.log.LogHelper;
import com.wubo.sec.log.LogState;
import com.wubo.sec.model.Authority;
import com.wubo.sec.model.User;
import com.wubo.sec.service.IUserAuthService;
import com.wubo.sec.util.ArrayUtils;
import com.wubo.spring.hibernate.BaseHibernateDao;

/**
 * @author wubo
 * @CreateDate 2010-8-8
 * @version 1.0.01
 */
@Service
@SuppressWarnings("unchecked")
public class UserAuthService implements IUserAuthService, ApplicationListener<ApplicationEvent> {
	@Autowired
	private BaseHibernateDao dao;
	
	public BaseHibernateDao getDao() {
		return dao;
	}

	public void setDao(BaseHibernateDao dao) {
		this.dao = dao;
	}
	/* (non-Javadoc)
	 * @see com.asc.sf.service.IUserAuthService#getAuthCodes(java.lang.String)
	 */
	public List<String> getAuthCodes(String username) {
		return dao.find("select a.code from Authority a inner join a.users u where u.username = ?", new Object[]{username});
	}

	/* (non-Javadoc)
	 * @see com.asc.sf.service.IUserAuthService#relate(java.lang.String, java.lang.String[])
	 */
	public void relate(UserAuthRelate relate) {
		String username = relate.getUsername();
		String[] authCodes = relate.getAuthCodes();
		
		User user = dao.get(User.class, username);
		
		StringBuilder sb = new StringBuilder();
		if(authCodes != null && authCodes.length > 0){
			List<Authority> auths = dao.find("from Authority a where a.code in ("+ArrayUtils.split(authCodes, ",", "'")+")");
			
			for(int i=0; i<auths.size(); i++){
				if(i>0){sb.append(",");}
				Authority temp = auths.get(i);
				if(LogState.isLogCode()){
					sb.append(temp.getCode()+"("+temp.getName()+")");
				}else{
					sb.append(temp.getName());
				}
			}
			
			user.setUserAuthorities(new HashSet<Authority>(auths));
		}else{
			user.setUserAuthorities(null);
		}
		dao.update(user);
		
		
		if(LogState.isLogCode()){
			LogHelper.actionLog(LangUtil.get("RelateUserAuth"), LangUtil.get("UserAuthDetail", username+"("+user.getUserText()+")", sb.toString()));
		}else{
			LogHelper.actionLog(LangUtil.get("RelateUserAuth"), LangUtil.get("UserAuthDetail", user.getUserText(), sb.toString()));
		}
		
	
	}

	public void onApplicationEvent(ApplicationEvent event) {
		if(event instanceof AuthorityEvent){
			AuthorityEvent authEvent = (AuthorityEvent) event;
			if( authEvent.getType() == AuthorityEvent.DELETE ){
				dao.executeSQL("DELETE FROM SEC_USER_AUTH WHERE AUTH_REL = ?", authEvent.getEntity().getCode());
			}
		}
	}
}
